const os = require('os');

const vmwarePattern = /VMware/i;
const vitrualBoxPattern = /VirtualBox/i;

/**
 * 网络工具类
 */
export abstract class NetworkUtils {
  /**
   * 获取本机所有IP
   * 排除了Windows上的VirtualBox,VMware虚拟机的网卡
   * @param excludeLocalhost 排除127.0.0.1
   */
  static getLocalIpAddrs(excludeLocalhost = false): string[] {
    const ips = [];
    const networks = os.networkInterfaces();
    const names = Object.keys(networks);
    for (const name of names) {
      if (vmwarePattern.test(name) || vitrualBoxPattern.test(name)) {
        continue;
      }

      const values = networks[name];
      for (const networkItem of values) {
        if (networkItem.family === 'IPv4') {
          if (excludeLocalhost && networkItem.address === '127.0.0.1') {
            continue;
          }
          ips.push(networkItem.address);
        }
      }
    }
    return ips;
  }

  /**
   * 返回跟给定ip同一网络相同的所有IP(xxx.xxx.xxx.1 ~ 254)
   * @param ip
   * @param excludeSelf 排除给定的IP
   */
  static getAllSameNetworkCardAddr(ip: string, excludeSelf = true): string[] {
    const ips: string[] = [];
    const dotLastIndex = ip.lastIndexOf('.') + 1;
    const self = +ip.substring(dotLastIndex);
    const prefix = ip.substring(0, dotLastIndex);
    for (let i = 1; i < 255; i++) {
      if (i === self) {
        continue;
      }
      ips.push(`${prefix}${i}`);
    }
    return ips;
  }
}
